<?php
#
# UNLVRandom: a dmBridge module for random objects
#
# Copyright © 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class UNLVRandomSQLiteDataStore extends DMSQLiteDataStore
implements UNLVRandomDataStore {

	protected static $instance;

	/**
	 * Wrapped by getSetupSQLForSQLite() in the main module class (UNLVRandom).
	 *
	 * @return array
	 */
	public static function getSetupSQL() {
		return array(
			'CREATE TABLE "random_object" (
				"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
				"alias" VARCHAR NOT NULL,
				"ptr" INTEGER NOT NULL
			);'
		);
	}

	/**
	 * Wrapped by getUpgradeSQLForSQLite() in the main module class (UNLVRandom).
	 * 
	 * @return array
	 */
	public static function getUpgradeSQL() {
		return array(
			// currently empty because there is no previous version from which
			// to upgrade.
		);
	}

	/**
	 * @return self object
	 * @since 0.3
	 */
	public static function getInstance() {
		if (!self::$instance instanceof self) {
			self::$instance = new self;
		}
		return self::$instance;
	}

	/**
	 * @param DMObject obj
	 */
	public function addRandomObject(DMObject $obj) {
		$sql = "INSERT INTO random_object(alias, ptr) VALUES(:alias, :ptr);";
		$params = array(
			':alias' => $obj->getCollection()->getAlias(),
			':ptr' => $obj->getPtr()
		);
		$this->write($sql, $params);
	}

	/**
	 * @return DMObject
	 */
	public function getRandomObject() {
		$sql = "SELECT alias, ptr FROM random_object ORDER BY RANDOM() LIMIT 1";
		$result = $this->read($sql, array());

		if (count($result)) {
			$collection = DMCollectionFactory::getCollection(
					$result[0]['alias']);
			$obj = DMObjectFactory::getObject($collection, $result[0]['ptr']);
			return $obj;
		}
		return null;
	}

	/**
	 * @param DMObject obj
	 * @return boolean
	 */
	public function isRandomObject(DMObject $obj) {
		foreach ($this->getRandomObjects() as $ro) {
			if ($obj->equals($ro)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @return array Array of DMObjects
	 */
	public function getRandomObjects() {
		$sql = "SELECT alias, ptr FROM random_object ORDER BY RANDOM()";
		$result = $this->read($sql, array());

		$objects = array();
		foreach ($result as $row) {
			try {
				$collection = DMCollectionFactory::getCollection($row['alias']);
				$objects[] = DMObjectFactory::getObject($collection, $row['ptr']);
			} catch (DMUnavailableModelException $e) {
				// nothing we can do; skip
			}
		}
		return $objects;
	}

}
